#pragma once

#include "global.h"

class Map
{
private:
	char ** m_map;
	int ** m_map_colors;
	int m_color;
	int m_x, m_y;
	int m_width, m_height;
public:
	int getX(){return m_x;}
	int getY(){return m_y;}
	void setX(int v){m_x = v;}
	void setY(int v){m_y = v;}
	int getWidth(){return m_width;}
	int getHeight(){return m_height;}
	void addMotion(int dx, int dy){m_x += dx; m_y += dy;}
	char get(int x, int y)
	{
		return m_map[y][x];
	}
	void set(int x, int y, char v)
	{
		m_map[y][x] = v;
	}
	int getColor(int x, int y)
	{
		return m_map_colors[y][x];
	}
	void setColor(int x, int y, int v)
	{
		m_map_colors[y][x] = v;
	}
	void set(int x, int y, char v, int c)
	{
		m_map[y][x] = v;
		m_map_colors[y][x] = c;
	}

	Map()
	{
		m_map = 0;
		m_map_colors = 0;
		m_x = 0;
		m_y = 0;
		m_color = 0;
		m_width = 0;
		m_height = 0;
	}

	bool load(char * a_filename)
	{
		fstream file(a_filename);

		if(!file.is_open())
			return false;

		file >> m_width >> m_height >> m_color;

		m_map = new char * [m_height];
		m_map_colors = new int * [m_height];
		for(int i = 0; i < m_height; ++i)
		{
			m_map[i] = new char [m_width];
			m_map_colors[i] = new int [m_width];
		}

		int x = 0, y = 0, input;

		while(file.good())
		{
			//this gets the character
			input  = file.get();

			//this makes sure its not an invalid character
			//and if it is, start at the top of the loop again
			if(input == '\n' || input == '\r' || input == -1)
				continue;

			//if there are too many characters
			if(y >= m_height)
			{
				printf("too many letters\n");
				break;
			}
			//set the data
			m_map[y][x] = input;
			m_map_colors[y][x] = m_color;
			x++;
			//when we get to the edge
			if(x >= m_width)
			{
				x = 0;
				y++;
			}
		}
		file.close();
		return true;
	}

	void draw(int a_x, int a_y)
	{
		for(int y = 0; y < m_height; ++y)
		{			
			for(int x = 0; x < m_width; ++x)
			{
				if(m_map[y][x] != ' ')
				{
					setConsoleColor(m_map_colors[y][x]);
					setConsoleCursor(a_x+x, a_y+y);
					putchar(m_map[y][x]);
				}
			}
		}
	}

	void draw()
	{
		draw(m_x, m_y);
	}

	void draw(Map & screen)
	{
		draw(m_x, m_y, screen);
	}

	void draw(int a_x, int a_y, Map & screen)
	{
		for(int y = 0; y < m_height; ++y)
		{
			for(int x = 0; x < m_width; ++x)
			{
				//setConsoleColor((int)(m_map_colors.getColor(a_x + x, a_y + y)));
				setConsoleColor(m_map_colors[y][x]);
				screen.set(a_x + x, a_y + y, m_map[y][x]);
			}
		}
	}

	void release()
	{
		if(m_map)
		{
			for(int i = 0; i < m_height; ++i)
			{
				delete [] m_map[i];
			}
			delete [] m_map;
		}
		if(m_map_colors)
		{
			for(int i = 0; i < m_height; ++i)
			{
				delete [] m_map_colors[i];
			}
			delete [] m_map_colors;
		}
		m_width = 0;
		m_height = 0;
		m_map = 0;
		m_map_colors = 0;
		m_color = 0;
		
	}
	~Map()
	{
		release();
	}
	
};//end of class Map